package com.whmskj.xjlhbc.mobile.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whmskj.xjlhbc.domain.Bctj14ProductionMonthlyCompletion;
import com.whmskj.xjlhbc.domain.Bctj18wshopydday;
import com.whmskj.xjlhbc.domain.Bctj18wshopydqk;
import com.whmskj.xjlhbc.domain.CompletionOfProductionDayBctj14;
import com.whmskj.xjlhbc.mapper.Bctj14ProductionMonthlyCompletionMapper;
import com.whmskj.xjlhbc.mapper.Bctj18wshopyddayMapper;
import com.whmskj.xjlhbc.mapper.Bctj18wshopydqkMapper;
import com.whmskj.xjlhbc.mapper.CompletionOfProductionDayBctj14Mapper;
import com.whmskj.xjlhbc.mobile.GetStartDate;
import com.whmskj.xjlhbc.mobile.service.IMobileDashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.*;

/**
 * 移动端首页数据聚合服务实现
 */
@Service("mobileHomeDashboardServiceImpl")
public class MobileDashboardServiceImpl implements IMobileDashboardService {

    @Autowired
    private Bctj14ProductionMonthlyCompletionMapper monthlyCompletionMapper;

    @Autowired
    private CompletionOfProductionDayBctj14Mapper dailyCompletionMapper;

    @Autowired
    private Bctj18wshopydqkMapper monthlyElectricityMapper;

    @Autowired
    private Bctj18wshopyddayMapper dailyElectricityMapper;

    @Override
    public Map<String, Object> getMobileHomeData() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取产量完成情况
        result.put("productionCompletion", getProductionCompletion());
        
        // 获取用电情况
        result.put("electricityUsage", getElectricityUsage());
        
        return result;
    }

    @Override
    public Map<String, Object> getProductionCompletion() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前月份数据
        int year = DateUtil.date().year();
        int month = GetStartDate.getMonthValue();
        
        LambdaQueryWrapper<Bctj14ProductionMonthlyCompletion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Bctj14ProductionMonthlyCompletion::getYear, year)
               .eq(Bctj14ProductionMonthlyCompletion::getMonth, month)
               .last("limit 1");
        
        Bctj14ProductionMonthlyCompletion monthlyData = monthlyCompletionMapper.selectOne(wrapper);
        
        // 整经数据
        Map<String, Object> zjData = new HashMap<>();
        if (monthlyData != null) {
            zjData.put("plannedProduction", formatNumber(monthlyData.getZjjhcl()));
            zjData.put("actualProduction", formatNumber(monthlyData.getZjwccl()));
            zjData.put("completionRate", calculateCompletionRate(monthlyData.getZjjhcl(), monthlyData.getZjwccl()));
        } else {
            zjData.put("plannedProduction", "0.00");
            zjData.put("actualProduction", "0.00");
            zjData.put("completionRate", "0.0%");
        }
        result.put("整经", zjData);
        
        // 浆纱数据
        Map<String, Object> jsData = new HashMap<>();
        if (monthlyData != null) {
            jsData.put("plannedProduction", formatNumber(monthlyData.getJsjhcl()));
            jsData.put("actualProduction", formatNumber(monthlyData.getJswccl()));
            jsData.put("completionRate", calculateCompletionRate(monthlyData.getJsjhcl(), monthlyData.getJswccl()));
        } else {
            jsData.put("plannedProduction", "0.00");
            jsData.put("actualProduction", "0.00");
            jsData.put("completionRate", "0.0%");
        }
        result.put("浆纱", jsData);
        
        // 织布数据
        Map<String, Object> zbData = new HashMap<>();
        if (monthlyData != null) {
            zbData.put("plannedProduction", formatNumber(monthlyData.getZbsjjhcl()));
            zbData.put("actualProduction", formatNumber(monthlyData.getZbsjwccl()));
            zbData.put("completionRate", calculateCompletionRate(monthlyData.getZbsjjhcl(), monthlyData.getZbsjwccl()));
        } else {
            zbData.put("plannedProduction", "0.00");
            zbData.put("actualProduction", "0.00");
            zbData.put("completionRate", "0.0%");
        }
        result.put("织布", zbData);
        
        // 整理数据
        Map<String, Object> zlData = new HashMap<>();
        if (monthlyData != null) {
            zlData.put("plannedProduction", formatNumber(monthlyData.getZljhcl()));
            zlData.put("actualProduction", formatNumber(monthlyData.getZlwccl()));
            zlData.put("completionRate", calculateCompletionRate(monthlyData.getZljhcl(), monthlyData.getZlwccl()));
        } else {
            zlData.put("plannedProduction", "0.00");
            zlData.put("actualProduction", "0.00");
            zlData.put("completionRate", "0.0%");
        }
        result.put("整理", zlData);
        
        return result;
    }

    @Override
    public Map<String, Object> getElectricityUsage() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前月份数据
        int year = DateUtil.date().year();
        int month = GetStartDate.getMonthValue();
        
        LambdaQueryWrapper<Bctj18wshopydqk> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Bctj18wshopydqk::getYear, String.valueOf(year))
               .eq(Bctj18wshopydqk::getMonth, String.valueOf(month))
               .last("limit 1");
        
        Bctj18wshopydqk monthlyData = monthlyElectricityMapper.selectOne(wrapper);
        
        // 总用电数据
        Map<String, Object> totalData = new HashMap<>();
        if (monthlyData != null) {
            totalData.put("totalConsumption", formatNumber(monthlyData.getTotalsumption()));
            totalData.put("totalCost", formatNumber(monthlyData.getMzdf()));
            totalData.put("electricityPerMeter", formatNumber(monthlyData.getMsjwmyd()));
        } else {
            totalData.put("totalConsumption", "0.00");
            totalData.put("totalCost", "0.00");
            totalData.put("electricityPerMeter", "0.00");
        }
        result.put("总用电", totalData);
        
        // 准整车间数据
        Map<String, Object> zzData = new HashMap<>();
        if (monthlyData != null) {
            zzData.put("totalConsumption", formatNumber(monthlyData.getMzzdh()));
            zzData.put("totalCost", formatNumber(monthlyData.getMzzdf()));
            zzData.put("electricityPerMeter", formatNumber(monthlyData.getMzzwmyd()));
        } else {
            zzData.put("totalConsumption", "0.00");
            zzData.put("totalCost", "0.00");
            zzData.put("electricityPerMeter", "0.00");
        }
        result.put("准整车间", zzData);
        
        // 织布车间数据
        Map<String, Object> zbData = new HashMap<>();
        if (monthlyData != null) {
            zbData.put("totalConsumption", formatNumber(monthlyData.getMzbdh()));
            zbData.put("totalCost", formatNumber(monthlyData.getMzbdf()));
            zbData.put("electricityPerMeter", formatNumber(monthlyData.getMzbwmyd1()));
        } else {
            zbData.put("totalConsumption", "0.00");
            zbData.put("totalCost", "0.00");
            zbData.put("electricityPerMeter", "0.00");
        }
        result.put("织布车间", zbData);
        
        return result;
    }

    @Override
    public Map<String, Object> getProductionTrend(String process, Integer days) {
        Map<String, Object> result = new HashMap<>();
        
        // 处理空值参数
        if (process == null) {
            process = "整经"; // 默认工序
        }
        
        // 获取当前盘存月的日期范围
        // 使用GetStartDate.getMonthStartDate()获取盘存月开始日期
        String monthStartDateStr = GetStartDate.getMonthStartDate();
        LocalDate firstDayOfMonth = LocalDate.parse(monthStartDateStr.substring(0, 10));
        
        // 计算盘存月结束日期（下个月20号）
        LocalDate lastDayOfMonth = firstDayOfMonth.plusMonths(1).withDayOfMonth(20);
        
        // 如果指定了天数，则限制查询范围
        if (days != null && days > 0) {
            LocalDate endDate = LocalDate.now();
            LocalDate startDate = endDate.minusDays(days - 1);
            
            // 确保查询范围在当前盘存月内
            if (startDate.isBefore(firstDayOfMonth)) {
                startDate = firstDayOfMonth;
            }
            if (endDate.isAfter(lastDayOfMonth)) {
                endDate = lastDayOfMonth;
            }
            
            firstDayOfMonth = startDate;
            lastDayOfMonth = endDate;
        }
        
        List<String> dates = new ArrayList<>();
        List<Double> plannedData = new ArrayList<>();
        List<Double> actualData = new ArrayList<>();
        
        // 查询当前盘存月的每日数据
        LambdaQueryWrapper<CompletionOfProductionDayBctj14> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(CompletionOfProductionDayBctj14::getStatisticsDate, 
                       firstDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                       lastDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
               .orderByAsc(CompletionOfProductionDayBctj14::getStatisticsDate);
        
        List<CompletionOfProductionDayBctj14> dailyDataList = dailyCompletionMapper.selectList(wrapper);
        
        // 创建日期到数据的映射
        Map<String, CompletionOfProductionDayBctj14> dataMap = new HashMap<>();
        for (CompletionOfProductionDayBctj14 dailyData : dailyDataList) {
            if (dailyData.getStatisticsDate() != null) {
                dataMap.put(dailyData.getStatisticsDate(), dailyData);
            }
        }
        
        // 生成完整的日期序列
        LocalDate currentDate = firstDayOfMonth;
        while (!currentDate.isAfter(lastDayOfMonth)) {
            String dateStr = currentDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            dates.add(dateStr);
            
            CompletionOfProductionDayBctj14 dailyData = dataMap.get(dateStr);
            if (dailyData != null) {
                // 根据工序选择对应数据
                switch (process) {
                    case "整经":
                        plannedData.add(formatDouble(dailyData.getZjjhcl()));
                        actualData.add(formatDouble(dailyData.getZjwccl()));
                        break;
                    case "浆纱":
                        plannedData.add(formatDouble(dailyData.getJsjhcl()));
                        actualData.add(formatDouble(dailyData.getJswccl()));
                        break;
                    case "织布":
                        plannedData.add(formatDouble(dailyData.getZbzbjhcl()));
                        actualData.add(formatDouble(dailyData.getZbzbwccl()));
                        break;
                    case "整理":

                        plannedData.add(0.0);
                        actualData.add(0.0);
                        break;
                    default:
                        // 默认返回整经数据
                        plannedData.add(formatDouble(dailyData.getZjjhcl()));
                        actualData.add(formatDouble(dailyData.getZjwccl()));
                        break;
                }
            } else {

                plannedData.add(0.0);
                actualData.add(0.0);
            }
            
            currentDate = currentDate.plusDays(1);
        }
        
        result.put("dates", dates);
        result.put("plannedProduction", plannedData);
        result.put("actualProduction", actualData);
        
        return result;
    }

    @Override
    public Map<String, Object> getElectricityTrend(String workshop, Integer days) {
        Map<String, Object> result = new HashMap<>();
        
        // 处理空值参数
        if (workshop == null) {
            workshop = "总用电"; // 默认车间
        }
        
        // 获取当前盘存月的日期范围
        // 使用GetStartDate.getMonthStartDate()获取盘存月开始日期
        String monthStartDateStr = GetStartDate.getMonthStartDate();
        LocalDate firstDayOfMonth = LocalDate.parse(monthStartDateStr.substring(0, 10));
        
        // 计算盘存月结束日期（下个月20号）
        LocalDate lastDayOfMonth = firstDayOfMonth.plusMonths(1).withDayOfMonth(20);
        
        // 如果指定了天数，则限制查询范围
        if (days != null && days > 0) {
            LocalDate endDate = LocalDate.now();
            LocalDate startDate = endDate.minusDays(days - 1);
            
            // 确保查询范围在当前盘存月内
            if (startDate.isBefore(firstDayOfMonth)) {
                startDate = firstDayOfMonth;
            }
            if (endDate.isAfter(lastDayOfMonth)) {
                endDate = lastDayOfMonth;
            }
            
            firstDayOfMonth = startDate;
            lastDayOfMonth = endDate;
        }
        
        List<String> dates = new ArrayList<>();
        List<Double> consumptionData = new ArrayList<>();
        List<Double> costData = new ArrayList<>();
        
        // 查询当前盘存月的每日数据
        LambdaQueryWrapper<Bctj18wshopydday> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(Bctj18wshopydday::getStatisticsDate,
                       firstDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                       lastDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
               .orderByAsc(Bctj18wshopydday::getStatisticsDate);
        
        List<Bctj18wshopydday> dailyDataList = dailyElectricityMapper.selectList(wrapper);
        
        // 创建日期到数据的映射，方便查找
        Map<String, Bctj18wshopydday> dataMap = new HashMap<>();
        for (Bctj18wshopydday dailyData : dailyDataList) {
            if (dailyData.getStatisticsDate() != null) {
                dataMap.put(dailyData.getStatisticsDate(), dailyData);
            }
        }
        
        // 生成完整的日期序列
        LocalDate currentDate = firstDayOfMonth;
        while (!currentDate.isAfter(lastDayOfMonth)) {
            String dateStr = currentDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            dates.add(dateStr);
            
            Bctj18wshopydday dailyData = dataMap.get(dateStr);
            if (dailyData != null) {
                // 根据车间选择对应数据
                switch (workshop) {
                    case "总用电":
                        consumptionData.add(formatDoubleFromString(dailyData.getTotalsumption()));
                        costData.add(formatDoubleFromString(dailyData.getMzdf()));
                        break;
                    case "准整车间":
                        consumptionData.add(formatDoubleFromString(dailyData.getMzzdh()));
                        costData.add(formatDoubleFromString(dailyData.getMzzdf()));
                        break;
                    case "织布车间":
                        consumptionData.add(formatDoubleFromString(dailyData.getMzbdh()));
                        costData.add(formatDoubleFromString(dailyData.getMzbdf()));
                        break;
                    default:
                        // 默认返回总用电数据
                        consumptionData.add(formatDoubleFromString(dailyData.getTotalsumption()));
                        costData.add(formatDoubleFromString(dailyData.getMzdf()));
                        break;
                }
            } else {

                consumptionData.add(0.0);
                costData.add(0.0);
            }
            
            currentDate = currentDate.plusDays(1);
        }
        
        result.put("dates", dates);
        result.put("dailyConsumption", consumptionData);
        result.put("dailyCost", costData);
        
        return result;
    }

    @Override
    public Map<String, Object> getWorkshopElectricity(String workshopName) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前月份数据
        int year = DateUtil.date().year();
        int month = GetStartDate.getMonthValue();
        
        LambdaQueryWrapper<Bctj18wshopydqk> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Bctj18wshopydqk::getYear, String.valueOf(year))
               .eq(Bctj18wshopydqk::getMonth, String.valueOf(month))
               .last("limit 1");
        
        Bctj18wshopydqk monthlyData = monthlyElectricityMapper.selectOne(wrapper);
        
        // 始终返回完整的字段结构
        switch (workshopName) {
            case "总用电":
                if (monthlyData != null) {
                    result.put("totalConsumption", formatNumber(monthlyData.getTotalsumption()));
                    result.put("totalCost", formatNumber(monthlyData.getMzdf()));
                    result.put("electricityPerMeter", formatNumber(monthlyData.getMsjwmyd()));
                } else {
                    result.put("totalConsumption", "0.00");
                    result.put("totalCost", "0.00");
                    result.put("electricityPerMeter", "0.00");
                }
                break;
            case "准整车间":
                if (monthlyData != null) {
                    result.put("totalConsumption", formatNumber(monthlyData.getMzzdh()));
                    result.put("totalCost", formatNumber(monthlyData.getMzzdf()));
                    result.put("electricityPerMeter", formatNumber(monthlyData.getMzzwmyd()));
                } else {
                    result.put("totalConsumption", "0.00");
                    result.put("totalCost", "0.00");
                    result.put("electricityPerMeter", "0.00");
                }
                break;
            case "织布车间":
                if (monthlyData != null) {
                    result.put("totalConsumption", formatNumber(monthlyData.getMzbdh()));
                    result.put("totalCost", formatNumber(monthlyData.getMzbdf()));
                    result.put("electricityPerMeter", formatNumber(monthlyData.getMzbwmyd1()));
                } else {
                    result.put("totalConsumption", "0.00");
                    result.put("totalCost", "0.00");
                    result.put("electricityPerMeter", "0.00");
                }
                break;
            default:
                result.put("error", "不支持的车间名称");
                break;
        }
        
        return result;
    }

    /**
     * 计算完成比例
     */
    private String calculateCompletionRate(BigDecimal plannedProduction, BigDecimal actualProduction) {
        if (plannedProduction == null || actualProduction == null) {
            return "0.0%";
        }
        
        // 如果计划产量为0，返回0%
        if (plannedProduction.compareTo(BigDecimal.ZERO) == 0) {
            return "0.0%";
        }
        
        // 计算完成比例：(实际产量 / 计划产量) * 100
        BigDecimal completionRate = actualProduction.divide(plannedProduction, 4, java.math.RoundingMode.HALF_UP)
                                                   .multiply(new BigDecimal("100"));
        
        return String.format("%.1f%%", completionRate);
    }

    /**
     * 格式化数字，保留2位小数 - 处理BigDecimal类型
     */
    private String formatNumber(BigDecimal value) {
        if (value == null) {
            return "0.00";
        }
        return String.format("%.2f", value);
    }

    /**
     * 格式化数字，保留2位小数 - 处理String类型
     */
    private String formatNumber(String value) {
        if (value == null || value.trim().isEmpty()) {
            return "0.00";
        }
        try {
            double num = Double.parseDouble(value);
            return String.format("%.2f", num);
        } catch (NumberFormatException e) {
            return "0.00";
        }
    }

    /**
     * 格式化百分比
     */
    private String formatPercentage(BigDecimal value) {
        if (value == null) {
            return "0.0%";
        }
        return String.format("%.1f%%", value);
    }

    /**
     * 格式化Double值 - 处理BigDecimal类型
     */
    private Double formatDouble(BigDecimal value) {
        if (value == null) {
            return 0.0;
        }
        return value.doubleValue();
    }

    /**
     * 格式化Double值 - 处理String类型
     */
    private Double formatDoubleFromString(String value) {
        if (value == null || value.trim().isEmpty()) {
            return 0.0;
        }
        try {
            return Double.parseDouble(value);
        } catch (NumberFormatException e) {
            return 0.0;
        }
    }
}
